package ru.st.selenium.pages;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;

import java.util.List;

public class HomePage extends AnyPage {

    public HomePage(PageManager pages) {
        super(pages);
    }

    @FindBy(xpath = "//a[@href='./?go=add']")
    private WebElement addMovieBtn;

    @FindBy(xpath = "//input[@id='q']")
    private WebElement searchInput;

    @FindBy(xpath = "//div[@id='results']//div[@class='title']")
    private List<WebElement> results;

    @FindBy(xpath = "//div[@id='results']")
    private WebElement result;

    public NewMoviePage clickNewMovieBtn() {
        addMovieBtn.click();
        return pages.newMoviePage;
    }

    public void clickOnSimpleMovie(String title) {
        WebElement movie = getWebDriver().findElement(By.xpath("//*[contains(text(), '"+title+"')]"));
        movie.click();
    }

    public HomePage ensurePageLoaded() {
        super.ensurePageLoaded();
        wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//a[@href='./?go=add']")));
        return this;
    }

    public HomePage searchForMovie(String movie) {
        searchInput.clear();
        searchInput.sendKeys(movie, Keys.RETURN);
        return this;
    }

    public SimpleMoviePage openFilmPage(String title) {
        for (WebElement movie : results) {
            if(movie.getText().contains("Test")) {
                movie.click();
            }
        }
        return pages.simpleMoviePage;
    }


    public int getSizeOffAllMoviesList() {
        return results.size();
    }

    public String getResult() {
        return result.getText();
    }

}
